﻿using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Xml;
using Microsoft.VisualStudio.Shell;

using CodeStream.Testing.WebAutomation;
using VSLangProj80;

namespace CodeStream.Testing.WebAutomation.Extension
{
    /// <summary>
    /// Generates the code for wrapper classes using the text template in the CodeStream.Testing.WebAutomation assembly.
    /// </summary>
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Interoperability", "CA1405:ComVisibleTypeBaseTypesShouldBeComVisible", Justification="The ClassInterfaceType is None and the base classes have no public methods")]
    [ComVisible(true)]
    [Guid("1AE178EC-7A70-40C5-A091-AB57A505028C")]
    [CodeGeneratorRegistration(typeof(UIDefinitionClassGenerator), "C# UI Definition Class Generator", vsContextGuids.vsContextGuidVCSProject, GeneratesDesignTimeSource = true)]
    [ProvideObject(typeof(UIDefinitionClassGenerator))]
    [ClassInterface(ClassInterfaceType.None)]
    public class UIDefinitionClassGenerator : BaseCodeGenerator
    {
        /// <summary>
        /// The method that does the actual work of generating code given the input file
        /// </summary>
        /// <param name="inputFileContent">File contents as a string</param>
        /// <returns>
        /// The generated code file as a byte-array
        /// </returns>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification="The TextReader will be closed when the XmlReader is closed.")]
        protected override byte[] GenerateCode(string inputFileContent)
        {
            try
            {
                using (XmlReader reader = XmlReader.Create(new StringReader(inputFileContent)))
                {
                    UIDefinitionClassTemplate template = new UIDefinitionClassTemplate(reader,
                        String.Format("{0}.{1}", FileNameSpace, Path.GetFileNameWithoutExtension(InputFilePath)));
                    return Encoding.UTF8.GetBytes(template.TransformText());
                }
            }
            catch (XmlException ex)
            {
                GeneratorError(0, ex.Message, (uint)ex.LineNumber - 1, (uint)ex.LinePosition - 1);
                return Encoding.UTF8.GetBytes("#error " + ex.Message);
            }
        }

        /// <summary>
        /// Gets the default extension for this generator
        /// </summary>
        /// <returns>
        /// String with the default extension for this generator
        /// </returns>
        protected override string GetDefaultExtension()
        {
            return ".cs";
        }
    }
}
